package com.example.demo.util.common;

import com.example.demo.common.response.BaseResponse;
import com.example.demo.common.response.ResponseData;
import io.swagger.annotations.ApiOperation;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * @program: xy-framework
 * @description: 响应体工具类
 * @author: FN
 * @create: 2020-03-31
 **/
public class ResponseDataUtil {

    /**
     * 获取响应体构造器
     *
     * @return
     */
    public static ResponseData.Builder responseDataBuild() {
        return new ResponseData.Builder();
    }

    /**
     * 正常响应封装体
     *
     * @param data
     * @param <T>
     * @return
     */
    public static <T> ResponseData responseData(T data) {
        return new ResponseData.Builder().data(data).message(buildMessage()).build();
    }

    public static <T> ResponseData responseData(T data,String message) {
        return new ResponseData.Builder().data(data).message(message).build();
    }
    public static ResponseData baseResponseData(BaseResponse baseResponse) {
        return new ResponseData.Builder().status(baseResponse.getStatus()).message(baseResponse.getMessage()).build();
    }

    /**
     * 获取接口描述说明
     * @return
     */
    public static String buildMessage() {
        HttpServletRequest request = WebUtils.getRequest();
        String[] requests = request.getRequestURI().split("/");
        String des = "";
        String methodName = requests[requests.length-1];
        StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
        StackTraceElement[] list = stackTraceElements;
        for(StackTraceElement stackTraceElement:list){
            String name = stackTraceElement.getMethodName();
            if (name.equals(methodName)) {
                String className = stackTraceElement.getClassName();
                try {
                    Class<?> tClass = Class.forName(className);
                    Method[] methods = tClass.getMethods();
                    for (Method method : methods) {
                        String adaptName = method.getName();
                        if (methodName.equals(adaptName)) {
                            if (method.isAnnotationPresent(ApiOperation.class)) {
                                ApiOperation apiOperation = method.getAnnotation(ApiOperation.class);
                                des = apiOperation.value();
                                break;
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        StringBuilder message = new StringBuilder("请求处理成功 [ ");
        message.append(des)
                .append(" ]");
        return message.toString();
    }

}
